<template>
  <div class="app-main-plus beautify">
    <div class="search-container">
      <el-row :gutter="10">
        <el-col :xs="18" :sm="18" :md="18" :lg="18" :xl="18">
          <el-button class="back-btn" type="default" size="small" plain icon="el-icon-arrow-left" @click="goBack">返回</el-button>
        </el-col>
        <el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6">
          <div class="pull-right" v-if="canEditAdd()">
            <el-button v-show="!isDisabled" size="small" @click="submit(0)" type="default" :disabled="loading" >暂存</el-button>
            <el-button v-show="!isDisabled" size="small" @click="submit(1)" type="primary" :disabled="loading" >提交</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="content-container">
      <form-title title="基本信息">
        <zb-form
          v-loading="loading"
          v-bind="options"
          ref="form"
          :editable="canEditAdd()"
          :model="form">
        </zb-form>
      </form-title>
      <form-title :title="`物料明细`">
        <div slot="title-suffix" v-if="canEditAdd()">
          <span>到货日期：</span>
          <el-date-picker
            v-model="form.date"
            size="small"
            style="width: 180px;margin-right: 10px"
            value-format="yyyy-MM-dd"
            type="date"
          ></el-date-picker>
          <el-button v-show="!isDisabled" size="small" @click="appendAll" type="default" :disabled="loading" v-if="canEditAdd()">确定</el-button>
          <el-button v-show="!isDisabled" size="small" @click="addLine" type="primary" :disabled="loading" v-if="canEditAdd()">添加物料</el-button>
        </div>
        <el-table
          v-loading="loading" border ref="tableForm" :data="form.purchasePlanDetailList" max-height="500">
          <el-table-column type="index" label="序号" width="80"  align="center" fixed/>
          <el-table-column prop="productLine" label="物料分类" min-width="100" align="center" fixed show-overflow-tooltip></el-table-column>
          <el-table-column property="materialGroup" align="center" label="物料分组" min-width="120" fixed show-overflow-tooltip/>
          <el-table-column prop="srmCode" label="物料编码" min-width="180" align="center" fixed show-overflow-tooltip></el-table-column>
          <el-table-column prop="materialName" label="物料名称" min-width="160" align="center" fixed show-overflow-tooltip></el-table-column>
          <el-table-column prop="basicUnit" label="基本单位" min-width="100" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="qualityIndex" align="center" label="质量指标" min-width="180" show-overflow-tooltip/>
          <el-table-column property="version" align="center" label="版本号" min-width="120" show-overflow-tooltip/>
          <el-table-column property="versionTime" align="center" label="版本日期" min-width="120" show-overflow-tooltip/>
          <el-table-column property="materialSpecs" align="center" label="规格型号" min-width="120" show-overflow-tooltip/>
          <el-table-column prop="materialDesc" label="物料描述" min-width="180" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="需求数量" width="150" align="center">
            <template v-slot:header>
              <span style="display: flex;justify-content: center;"><span style="color: red" >*</span>需求数量</span>
            </template>
            <template  slot-scope="scope">
              <el-input v-model="scope.row.requireAmount" oninput="if(value>999999999)value=999999999;if(value<=0)value=0;value = Number(value.toString().match( /^\d+(?:\.\d{0,0})?/ ));" :disabled="!canEditAdd()" placeholder="请输入" type="number" max="999999999" min="0"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="需求到货时间" min-width="180" align="center">
            <template v-slot:header>
              <span style="display: flex;justify-content: center;"><span style="color: red" >*</span>需求到货时间</span>
            </template>
            <template  slot-scope="scope">
              <el-date-picker
                v-model="scope.row.requestArriveTime"
                size="small"
                style="width: 150px;"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择"
                v-if="canEditAdd()"
              ></el-date-picker>
              <span v-else> {{scope.row.requestArriveTime}} </span>
            </template>
          </el-table-column>
          <el-table-column property="到货数量" label="到货数量" align="center" min-width="120" show-overflow-tooltip>
            <template v-slot:header>
              <span style="display: flex;justify-content: center;">到货数量</span>
            </template>
            <template  slot-scope="scope">
              <!--              <el-input v-model="scope.row.arriveAmount" oninput="if(value>999999999)value=999999999;if(value<=0)value=0;value = Number(value.toString().match( /^\d+(?:\.\d{0,2})?/ ));" :disabled="!canEditAdd()" placeholder="请输入" type="number" max="999999999" min="0"></el-input>-->
              <!--              <el-input v-model="scope.row.arriveAmount" oninput="if(value>999999999)value=999999999;if(value<=0)value=0;value = Number(value.toString().match( /^\d+(?:\.\d{0,2})?/ ));" :disabled="!canEditAdd()" placeholder="请输入" type="number" max="999999999" min="0"></el-input>-->
              {{scope.row.arriveAmount}}
            </template>
          </el-table-column>
<!--          <el-table-column property="安装数量" label="安装数量" align="center" min-width="120" show-overflow-tooltip>-->
<!--            <template  slot-scope="scope">-->
<!--              &lt;!&ndash;              <el-input v-model="scope.row.installAmount" oninput="if(value>999999999)value=999999999;if(value<=0)value=0;value = Number(value.toString().match( /^\d+(?:\.\d{0,2})?/ ));" :disabled="!canEditAdd()" placeholder="请输入" type="number" max="999999999" min="0"></el-input>&ndash;&gt;-->
<!--              &lt;!&ndash;              <el-input v-model="scope.row.installAmount" oninput="if(value>999999999)value=999999999;if(value<=0)value=0;value = Number(value.toString().match( /^\d+(?:\.\d{0,2})?/ ));" :disabled="!canEditAdd()" placeholder="请输入" type="number" max="999999999" min="0"></el-input>&ndash;&gt;-->
<!--              {{scope.row.installAmount}}-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column property="是否签订合同" label="是否签订合同" align="center" min-width="120" show-overflow-tooltip>
            <template  slot-scope="scope">
              <span v-if="scope.row.isSigned==1">是</span>
              <span v-if="scope.row.isSigned==0">否</span>
            </template>
          </el-table-column>
          <el-table-column property="操作" label="操作" align="center" fixed="right" min-width="120" show-overflow-tooltip v-if="canEditAdd()">
            <template  slot-scope="scope">
              <el-button class="el-icon-delete" size="mini" type="danger" @click="delLine(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </form-title>
      <form-title title="附件清单">
        <zb-form
          v-loading="loading"
          v-bind="options1"
          ref="form1"
          :editable="canEditAdd()"
          :model="form">
        </zb-form>
      </form-title>
    </div>

    <el-dialog :visible.sync="showDialog" title="选择物料明细" width="80%" append-to-body>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline" ref="queryForm">
        <el-form-item label="物料编码:" size="small" prop="srmCode">
          <el-input v-model="queryParams.srmCode" size="small" placeholder="请输入 物料编码" style="width: 160px" clearable/>
        </el-form-item>
        <el-form-item label="物料分类:" size="small" prop="productLine">
          <el-input v-model="queryParams.productLine" size="small" placeholder="请输入 物料分类" style="width: 160px" clearable/>
        </el-form-item>
        <el-form-item label="物料分组:" size="small" prop="materialGroup">
          <el-input v-model="queryParams.materialGroup" size="small" placeholder="请输入 物料分组" style="width: 160px" clearable/>
        </el-form-item>
        <el-form-item label="物料名称:" size="small" prop="materialName">
          <el-input v-model="queryParams.materialName" size="small" placeholder="请输入 物料名称" style="width: 160px" clearable/>
        </el-form-item>
        <el-form-item size="small">
          <el-button type="primary" size="small" @click="addLine()">查询</el-button>
<!--          <el-button type="primary" size="small" @click="resetQuery" plain>清空</el-button>-->
        </el-form-item>
      </el-form>
      <el-table
        @selection-change="handleSelectionChange"
        v-loading="loading" border ref="tableForm" :data="list" height="500">
        <el-table-column type="index" label="序号" width="80"  align="center" fixed/>
        <el-table-column prop="productLine" label="物料分类" min-width="100" align="center" fixed show-overflow-tooltip></el-table-column>
        <el-table-column prop="materialGroup" align="center" label="物料分组" min-width="120" fixed show-overflow-tooltip/>
        <el-table-column prop="srmCode" label="物料编码" min-width="180" align="center" fixed show-overflow-tooltip></el-table-column>
        <el-table-column prop="materialName" label="物料名称" min-width="160" align="center" fixed show-overflow-tooltip></el-table-column>
        <el-table-column prop="basicUnit" label="基本单位" min-width="160" align="center" fixed show-overflow-tooltip></el-table-column>
        <el-table-column prop="qualityIndex" align="center" label="质量指标" min-width="120" show-overflow-tooltip/>
        <el-table-column prop="version" label="版本号" min-width="100" align="center"></el-table-column>
        <el-table-column prop="versionTime" label="版本日期" min-width="100" align="center"></el-table-column>
        <el-table-column prop="materialSpecs" label="规格型号" min-width="100" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="materialDesc" label="物料描述" min-width="180" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column property="操作" align="center" label="操作" min-width="120" show-overflow-tooltip fixed="right">
          <template  slot-scope="scope">
            <el-button type="primary" size="mini" @click="selectLine(scope.row)">确定</el-button>
          </template>
        </el-table-column>
      </el-table>
      <BasePagination :that="this" ref="pagination"/>
      <div slot="footer" style="display: flex;justify-content: center;"><el-button type="default" @click="showDialog=false">取消</el-button></div>
    </el-dialog>

  </div>
</template>

<script>
  import {getDetailById, addForm, updateForm, checkedListForm} from "@/api/designManager/procurementPlan";
  import { checkedListForm as listForm } from "@/api/designManager/procurementPlan";
  import FormTitle from "@/views/components/FormTitle";
  import BaseBpm from "@/views/base/BaseBpm";
  import BasePagination from "@/views/base/BasePagination";
  import BaseIndex from "@/views/base/BaseIndex";
  import {newWindowBpm} from "@/utils/openBpm";
  import Index from "./index";
  import {getToken} from "@/utils/auth";
  import {minusDate} from "@/utils/dateUtils";
  import request from '@/utils/request'
  import store from "@/store";
  import router from "@/router";

  export default {
    name: "DesignManagerProcurementPlanDetail",
    components: { BaseBpm, BasePagination ,FormTitle,},
    extends:BaseIndex,
    watch:{},
    computed: {
    },
    data() {
      return {
        form: {
          purchasePlanDetailList:[]
        },
        page:{
          pageNum:1,
          pageSize:10,
          total:0,
          proName:'',
        },
        queryParams:{
          srmCode:'',
          productLine:'',
          materialGroup:'',
          materialName:'',
        },
        // 显示弹窗
        showDialog:false,
        options:{
          labelWidth: "160px",
          rules:{
            planName: [
              { required: true, message: '请输入 计划名称', trigger: 'blur' }
            ],
            projectName: [
              { required: true, message: '请选择 项目名称', trigger: 'blur' }
            ],
            planStartTime: [
              { required: true, message: '请选择 计划开始日期', trigger: 'blur' }
            ],
            planEndTime: [
              { required: true, message: '请选择 计划结束日期', trigger: 'blur' }
            ],
          },
          options:[
            {
              label: "计划名称",
              prop: "planName",
              type: 'text',
              exits:this.canEditAdd(),
              span: 8,
            },
            {
              label: "计划名称",
              prop: "planName",
              exits:!this.canEditAdd(),
              type: 'value',
              span: 8,
            },
            {
              label: "项目名称",
              prop: "projectName",
              type: "selectData",
              searchKey: "name",
              url: `${process.env.VUE_APP_BASE_API}/t-purchase-plan/listForPurchase`,
              props: {
                label: "projectName",
                value: "projectName"
              },
              createdRequest: false,
              searchIconVisible:true,
              filterAble:true,
              getDictSuccessStatus:0,
              getDictResultMap:{
                status:'data.code',
                data:'data.data',
                list:'data.data.records',
                total:'data.data.total',
              },
              clickClose:true,
              method:'post',
              params:{
                pageNum:1,
                pageSize:20,
              },
              dialogType:2,
              labelFields:['number','projectName'],
              labelFieldsName:['项目编码','项目名称'],
              searchLabel:['projectName'],
              searchLabelName:['项目名称'],
              headers: {
                Authorization: 'Bearer ' + getToken()
              },
              listeners:{
                dataChange:(val,val1,val2)=>{
                  this.$set(this.form,'projectId',val.projectId)
                  this.$set(this.form,'projectName',val.projectName)
                  this.$set(this.form,'companyName',val.companyName)
                  this.$set(this.form,'researchName',val.researchName)
                }
              },
              exits:this.canEditAdd(),
              span: 8,
            },
            {
              label: "项目名称",
              prop: "projectName",
              type: "value",
              exits:!this.canEditAdd(),
              span: 8,
            },
            {
              label: "所在公司",
              prop: "companyName",
              type: 'value',
              span: 8,
            },
            {
              label: "计划开始日期",
              prop: "planStartTime",
              type: 'date',
              valueFormat:"yyyy-MM-dd",
              span: 8,
            },
            {
              label: "计划结束日期",
              prop: "planEndTime",
              valueFormat:"yyyy-MM-dd",
              type: 'date',
              span: 8,
            },
            {
              span: 8,
            },
            {
              label: "申请人",
              prop: "createByName",
              type: 'value',
              show: this.$route.query.type!=='add',
              span: 8,
            },
            {
              label: "申请时间",
              prop: "createTime",
              type: 'value',
              show: this.$route.query.type!=='add',
              span: 8,
            },
            {
              show: this.$route.query.type!=='add',
              span: 8,
            },
          ]
        },
        options1:{
          labelWidth: "160px",
          rules:{
            fileInfoList: [
              { required: true, message: '请选择 附件清单', trigger: 'blur' }
            ],
          },
          options:[
            {
              label: '附件清单',
              prop: "fileInfoList",
              type: 'file',
              span: 24,
              limit:4,
              align: 'center',
              url:`${process.env.VUE_APP_BASE_API}/file/upload`,
              downUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              previewUrl:`${process.env.VUE_APP_BASE_API}/file/download`,
              headers:{
                Authorization:'Bearer '+getToken()
              },
              height:90,
              resultDataMap:{
                fileName:'',
                filePath:'',
                fileSize:'',
              }
            }
          ]
        },
      }
    },
    created(){
      this.init()
      // 查询详情
      if (this.$route.query.id){
        this.loading = true
        getDetailById(this.$route.query.id).then(res=>{
          if (res.code===0){
            if (res.data?.purchasePlanDetailList?.length){
              for (let i = 0; i < res.data?.purchasePlanDetailList?.length; i++) {
                let temp = res.data?.purchasePlanDetailList[i].baseMaterial
                if (temp) delete temp.id
                res.data.purchasePlanDetailList[i] = {...res.data?.purchasePlanDetailList[i],...temp}
              }
            }
            this.form = {...res.data};
          }
          this.loading = false
        }).catch(err=>{
          this.loading = false
        })
      }else{
        // 新增
        this.form.applyName = this.userInfo.name
        this.form.applyOa = this.userInfo.account
        this.form.createByName = this.userInfo.name
        this.form.createBy = this.userInfo.account
        this.form.createTime = this.$zbPlugins.timeFormat(new Date(),'yyyy-MM-dd hh:mm:ss')
        this.form.serialNumber = '自动生成'
      }
    },
    methods:{
      updateForm,
      addForm,
      init(){
      },
      listForm,
      // 新增行
      addLine(){
        this.showDialog = true;
        this.getList()
      },
      getList(){
        checkedListForm({...this.queryParams}).then(response => {
          if (response.status == 200) {
            this.list = response.data.list
            this.total = response.data.total
          }
        }).catch(()=>{this.loading = false});
      },
      appendAll(){
        this.$confirm('确定是否填充?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(this.form?.purchasePlanDetailList?.length){
            for (let i = 0; i < this.form?.purchasePlanDetailList?.length; i++) {
              this.$set(this.form.purchasePlanDetailList[i],'requestArriveTime',this.form.date)
            }
          }
        }).catch(() => {
        });
      },
      canEditAdd(){
        return this.$route.query.type=='edit' || this.$route.query.type=='add'
      },
      submit(type){
        console.log('列表',this.form)
        this.$refs.form.validate(valid=> {
          if (valid) {
            this.$refs.form1.validate(valid1=> {
              if (valid1){
                if (this.checkData()) {
                  this.loading = true
                  this.form.type = type
                  // 处理数据给后端
                  if (this.form.id != undefined) {
                    updateForm(this.form).then(response => {
                      this.msgSuccess("修改成功");
                      this.loading = false;
                      if (response.code==0){
                        if (type==1){
                          newWindowBpm(response.data,null,{path:`/designManager/designManagerProcurementPlan`},true, Index)
                        }
                        this.$store.dispatch('tagsView/delView',this.$route)
                        this.$store.dispatch('tagsView/delCachedView', Index).then(() => {
                          this.goBack()
                        })
                      }
                    }).catch(()=>{this.loading = false});
                  } else {
                    addForm(this.form).then(response => {
                      this.msgSuccess("新增成功");
                      this.loading = false;
                      if (response.code==0){
                        if (type==1){
                          newWindowBpm(response.data,null,{path:`/designManager/designManagerProcurementPlan`},true, Index)
                        }
                        this.$store.dispatch('tagsView/delView',this.$route)
                        this.$store.dispatch('tagsView/delCachedView', Index).then(() => {
                          this.goBack()
                        })
                      }
                    }).catch(()=>{this.loading = false});
                  }
                }
              }
            })
          }
        })
      },
      // 删除行
      delLine(index){
        this.form.purchasePlanDetailList.splice(index,1)
      },
      // 选择行
      selectLine(row){
        let one = this.form.purchasePlanDetailList?.filter(item=>item.srmCode===row.srmCode)
        if (!one?.length){
          this.form.purchasePlanDetailList?.push({...row,id:''})
          return this.$message.success('添加成功')
        }
        return this.$message.warning('已经存在，请勿重复添加')
      },
      /**
       *校验数据
       */
      checkData(){

        if (minusDate(this.form?.planEndTime,this.form?.planStartTime)<=0){
          return this.$message.warning('计划开始日期 不能比 计划结束日期大') && false
        }

        if (!this.form?.purchasePlanDetailList?.length){
          return this.$message.warning('请添加物料清单项') && false
        }
        if (this.form.purchasePlanDetailList?.length){
          for(let i=0;i<this.form.purchasePlanDetailList.length;i++){
            const { requireAmount, requestArriveTime } = this.form.purchasePlanDetailList[i];
            if(!requireAmount) return this.$message.warning(`请填写第${i+1}行 需求数量`) && false;
            if(!requestArriveTime) return this.$message.warning(`请选择第${i+1}行 需求到货时间`) && false;
          }
        }
        return true
      },
      goBack() {
        this.$router.push({
          path:"/designManager/designManagerProcurementPlan",
        });
      },
    },
  }
</script>
